package com.jshan.blog.context;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

public class LoginInfoContext {
    // new ThreadLocal<>();  这个对于上下文切换会出现问题
    // new InheritableThreadLocal<>() 多线程复用会出现问题
    // new TransmitThreadLocal<>() 使用这个
    private static final InheritableThreadLocal<Map<String, Object>> THREAD_LOCAL
            = new InheritableThreadLocal<>();


    public static void set(String key, Object value) {
        Map<String, Object> map = getThreadLocalMap();
        map.put(key, value);
    }

    public static Object get(String key){
        Map<String, Object> threadLocalMap = getThreadLocalMap();
        return threadLocalMap.get(key);
    }

    public static String getUserId(){
        return (String) getThreadLocalMap().get("userId");
    }
    public static String getUserName(){
        return (String) getThreadLocalMap().get("username");
    }

    public static void remove(){
        THREAD_LOCAL.remove();
    }


    private static Map<String, Object> getThreadLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (Objects.isNull(map)){
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

}
